import { ref, computed } from 'vue'
import { BackgroundAudioPlayer } from './backgroundAudioPlayer'
import { VideoPlayer } from './videoPlayer'
import { useToast } from 'wot-design-uni'
import type { MediaView } from '@/api/children.typing'

export const useMediaPlayer = () => {
  const audioPlayer = new BackgroundAudioPlayer()
  const videoPlayer = new VideoPlayer()
  const toast = useToast()

  // 共享播放状态
  const playingItem = computed(() => audioPlayer.playingItem.value || videoPlayer.playingItem.value)
  const isPlaying = computed(() => audioPlayer.isPlaying.value || videoPlayer.isPlaying.value)
  const showVideoPlayer = ref(false)

  // 播放器弹窗相关
  const showPlaylist = ref(false)
  const ITEMS_PER_TAB = 10 // 每个标签页显示的项数
  const currentTabPage = ref(0) // 当前选中的标签页索引
  const playlistData = ref<{ list: MediaView[]; total: number; pageNum: number }>({
    list: [],
    total: 0,
    pageNum: 0,
  })
  const playlistLoading = ref(false)
  const lastPlaylistTab = ref(0) // 记录上次打开的标签页索引

  // 计算播放列表标签
  const playlistTabs = computed(() => {
    const tabs = []
    const totalTabs = Math.ceil(playlistData.value.total / ITEMS_PER_TAB)

    for (let i = 0; i < totalTabs; i++) {
      const start = i * ITEMS_PER_TAB + 1
      const end = Math.min((i + 1) * ITEMS_PER_TAB, playlistData.value.total)
      tabs.push({
        label: `${start}-${end}集`,
        startIndex: i * ITEMS_PER_TAB,
        endIndex: end,
      })
    }

    return tabs
  })

  // 控制栏显示状态
  const loadingPrev = ref(false) // 上一曲加载中
  const loadingNext = ref(false) // 下一曲加载中

  // 播放控制
  const toggleAudio = (item: MediaView, progressSeconds = 0) =>
    audioPlayer.toggle(item, progressSeconds)

  const stopAudio = () => audioPlayer.stop()

  const handleMediaPlay = async (item: MediaView) => {
    if (audioPlayer.checkMediaExpiration(item)) {
      toast.warning('内容已过期，请刷新页面')
      return
    }

    if (item.mediaType === 'audio') {
      toggleAudio(item)
    } else {
      showVideoPlayer.value = true
      videoPlayer.play(item)
      console.log('showVideoPlayer', showVideoPlayer.value)
    }
  }

  // 视频播放器关闭
  const closeVideoPlayer = () => {
    if (playingItem.value) {
      audioPlayer.savePlaybackProgress(playingItem.value.id, videoPlayer.currentTime.value)
    }
    videoPlayer.stop()
    showVideoPlayer.value = false
  }

  // 时间格式化
  const formatTime = (seconds: number) => audioPlayer.formatTime(seconds)

  const handleAudioSeekChange = (value) => {
    // console.log('监听到拖动进度条事件', value)
    audioPlayer.play(playingItem.value, value)
  }

  const checkMediaExpiration = (item: MediaView) => audioPlayer.checkMediaExpiration(item)

  // 根据当前播放项计算标签页索引
  const calculateTabForCurrentItem = () => {
    if (!playingItem.value) return 0

    return playlistData.value.pageNum - 1
  }

  // 从列表中选择播放
  const playFromList = (item) => {
    // 停止当前播放
    if (playingItem.value) {
      if (playingItem.value.mediaType === 'audio') {
        stopAudio()
      } else {
        closeVideoPlayer()
      }
    }

    // 播放新项目
    handleMediaPlay(item)
    // 更新最后播放的标签页
    lastPlaylistTab.value = currentTabPage.value
    showPlaylist.value = false
  }

  const playNextMedia = (mediaList: MediaView[]) => {
    if (loadingNext.value) return
    loadingNext.value = true
    try {
      // 获取当前播放项的索引
      const currentIndex = mediaList.findIndex(
        (item) => item.id === (playingItem.value?.id || playingItem.value?.id),
      )

      if (currentIndex === -1) {
        toast.warning('当前没有播放内容')
        return
      }

      // 计算下一首索引（循环播放）
      let nextIndex = currentIndex + 1
      if (nextIndex >= mediaList.length) {
        nextIndex = 0
      }

      const nextItem = mediaList[nextIndex]

      // 检查是否过期
      if (checkMediaExpiration(nextItem)) {
        toast.warning('下一首内容已过期，请刷新页面')
        return
      }

      // 停止当前播放
      if (playingItem.value) {
        stopAudio()
        closeVideoPlayer()
      }

      // 播放下一首
      handleMediaPlay(nextItem)
    } catch (error) {
      toast.error(`播放失败: ${error.message}`)
    } finally {
      loadingNext.value = false
    }
  }

  const playPrevMedia = (mediaList: MediaView[]) => {
    if (loadingPrev.value) return
    loadingPrev.value = true
    try {
      const currentIndex = mediaList.findIndex(
        (item) => item.id === (playingItem.value?.id || playingItem.value?.id),
      )

      if (currentIndex === -1) {
        toast.warning('当前没有播放内容')
        return
      }

      // 寻找上一个指定类型的媒体项
      let prevIndex = currentIndex
      let prevItem: MediaView | null = null
      let attempts = 0

      do {
        prevIndex = (prevIndex - 1 + mediaList.length) % mediaList.length
        prevItem = mediaList[prevIndex]
        attempts++

        // 检查是否过期
        if (!checkMediaExpiration(prevItem)) {
          break
        }

        prevItem = null
      } while (attempts < mediaList.length && prevIndex !== currentIndex)

      if (!prevItem) {
        toast.warning('没有找到上一个可播放的内容')
        return
      }

      // 停止当前播放
      if (playingItem.value) {
        stopAudio()
        closeVideoPlayer()
      }

      // 播放上一首
      handleMediaPlay(prevItem)
    } catch (error) {
      toast.error(`播放失败: ${error.message}`)
    } finally {
      loadingPrev.value = false
    }
  }

  return {
    playingItem,
    isPlaying,
    sliderValue: audioPlayer.sliderValue,
    showVideoPlayer,
    toggleAudio,
    stopAudio,
    handleMediaPlay,
    closeVideoPlayer,
    formatTime,
    videoPlayer,
    audioPlayer,
    handleAudioSeekChange,
    checkMediaExpiration,
    calculateTabForCurrentItem,
    playFromList,
    playlistLoading,
    loadingNext,
    loadingPrev,
    playlistTabs,
    currentTabPage,
    lastPlaylistTab,
    showPlaylist,
    ITEMS_PER_TAB,
    playlistData,
    playPrevMedia,
    playNextMedia,
  }
}
